<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Models\Permissions;
use App\Http\Models\Roles;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\DB;

/**
 * 权限组控制器
 */
class GroupController extends Controller
{
    use AuthenticatesUsers;

    //用户信息
    protected $userInfo;

    public function __construct()
    {
        $this->userInfo = auth()->user();
    }

    /**
     *  权限组列表，搜索数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function getList()
    {
        //获取所有按钮权限ID
        $request = request(['keywords', 'page', 'length']);

        $request['page'] = !empty($request['page']) ? $request['page'] : 1;
        $request['length'] = !empty($request['length']) ? $request['length'] : 10;
        $request['keywords'] = !empty($request['keywords']) ? $request['keywords'] : '';

        $where = ['page' => $request['page'], 'length' => $request['length'], 'keywords' => $request['keywords']];

        $data = Roles::getList($where);
        return respondWithData(0, $data, '请求成功');
    }

    /**
     * 获取组内用户
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupUsers()
    {
        //获取所有按钮权限ID
        $request = request(['role_id']);
        $request['role_id'] = !empty($request['role_id']) ? $request['role_id'] : 0;
        if (empty($request['role_id'])) {
            return respondWithData(0, [], '请求参数错误：role_id 不能为空');
        }

        $where = ['role_id' => $request['role_id']];
        $data = Roles::getGroupUsers($where);
        return respondWithData(0, $data, '请求成功');
    }

    /**
     * 组成员保存
     * @return \Illuminate\Http\JsonResponse
     */
    public function saveGroupUsers()
    {
        $request = request(['role_id', 'user_id_source', 'user_id_result']);

        if (empty($request['role_id'])) {
            return respondWithData(0, [], '请求参数错误：role_id不能为空');
        }

        $user_id_source = explode(',', $request['user_id_source']);
        $user_id_result = explode(',', $request['user_id_result']);

        $model_ids = array_diff($user_id_source, $user_id_result);
        $arr = array_diff($user_id_result, $user_id_source);

        $tmp = ['role_id' => $request['role_id'], 'model_type' => 'App\Http\Models\User'];
        $where['add'] = [];
        if ($arr) {
            foreach ($arr as $v) {
                $tmp['model_id'] = $v;
                $where['add'][] = $tmp;
            }
        }

        //增加的用户
        // $where['add']

        //删除的用户
        $where['role_id'] = $request['role_id'];
        $where['model_ids'] = $model_ids;

        $rt = Roles::saveGroupUsers($where);

        //清除权限缓存
        app()->make(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
        return respondWithData(0, [], '请求成功');
    }


    /**
     * 添加用户组
     * @return \Illuminate\Http\JsonResponse
     */
    public function addGroup()
    {
        try {
            $request = request(['role_name', 'permissions']);
            $request['role_name'] = trim($request['role_name']);
            $request['permissions'] = !empty($request['permissions']) ? trim($request['permissions']) : '';
            if (empty($request['role_name'])) {
                return respondWithData(0, [], '请求参数错误：role_name不能为空！');
            }
            // $role=Role::findById(9);
            $role = Role::create(['name' => $request['role_name']]);
            // $permissions=[37,42];
            //菜单权限id
            $permissions = explode(',', $request['permissions']);
            if ($permissions) {
                $role->syncPermissions($permissions);
            }
            return respondWithData(0, [], '请求成功');

        } catch (\Exception $exception) {

            return respondWithData(0, [], '请求失败：' . $exception->getMessage());
        }
    }

    /**
     * 编辑用户组
     * @return \Illuminate\Http\JsonResponse
     */
    public function editGroup()
    {
        try {
            DB::beginTransaction();

            $request = request(['role_id', 'role_name', 'permissions']);

            $request['role_name'] = trim($request['role_name']);
            $request['role_id'] = trim($request['role_id']);
            $request['permissions'] = !empty($request['permissions']) ? trim($request['permissions']) : '';

            if (empty($request['role_name']) || empty($request['role_id'])) {
                return respondWithData(0, [], '请求参数错误：role_name,role_id不能为空！');
            }

            //修改组名字
            //判断是否重复
            $model = new \App\Http\Models\Roles();
            $where = [
                'id' => $request['role_id'],
                'name' => $request['role_name'],
            ];

            $rt = $model::getRolesByWhere($where);
            if (!empty($rt)) {
                return respondWithData(0, [], '请求参数错误:role_name,不能重复 ');
            }
            //保存组名
            $model = $model::find($request['role_id']);
            $model->name = $request['role_name'];
            $model->save();

            //添加权限 会自动删除以前存在的权限
            $result = explode(',', $request['permissions']);
            $role = Role::findById($request['role_id']);
            $role->syncPermissions($result);
            DB::commit();
            return respondWithData(0, [], '请求成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return respondWithData(0, [], '请求失败：' . $exception->getMessage());
        }
    }


    /**
     * 删除用户组
     * @return void
     */
    public function delGroup()
    {
        $request = request(['role_id']);

        $M = new \App\Http\Models\Roles();

        $rt = $M->delRole($request['role_id']);

        if ($rt) {
            return respondWithData(0, [], '请求成功');
        } else {
            return respondWithData(0, [], '请求失败');
        }
    }

}
